package com.tanhua.server.interceptor;

import cn.hutool.core.convert.Convert;
import cn.hutool.json.JSONUtil;
import com.tanhua.server.utils.Cache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.MethodParameter;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.concurrent.TimeUnit;

/**
 * 作用：将Controller中返回的数据写入到redis中
 */
@ControllerAdvice
public class MyResponseBodyAdvice implements ResponseBodyAdvice {

    @Autowired
    private StringRedisTemplate redisTemplate;

    //缓存的总开关
    @Value("${tanhua.cache.enable}")
    private Boolean cacheEnable;

    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        return cacheEnable && methodParameter.hasMethodAnnotation(GetMapping.class)
                && methodParameter.hasMethodAnnotation(Cache.class);
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {

        if (null == body) {
            return body;
        }

        String cacheData;
        if (body instanceof String) {
            cacheData = (String) body;
        } else {
            cacheData = JSONUtil.toJsonStr(body);
        }

        //生成redis中的key
        String redisKey = RedisCacheInterceptor
                .createRedisKey(((ServletServerHttpRequest) serverHttpRequest).getServletRequest());


        //获取Cache注解，目的获取注解中的时间的长度
        Cache cache = methodParameter.getMethodAnnotation(Cache.class);

        //写数据到redis中，有效期时间单位是：秒
        this.redisTemplate.opsForValue().set(redisKey, cacheData,
                Convert.toLong(cache.time()), TimeUnit.SECONDS);

        return body;
    }
}
